package com.android.superobstacleavoider;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import javax.microedition.khronos.opengles.GL10;

public class Square {

	// The buffer holding the vertices
	protected FloatBuffer m_vertexBuffer;
	protected FloatBuffer m_colorBuffer;

	protected float m_angle = 0.0f;

	// The initial vertex definition
	protected float m_vertices[] = { -1.0f, -1.0f, 0.0f, // Bottom Left
			1.0f, -1.0f, 0.0f, // Bottom Right
			-1.0f, 1.0f, 0.0f, // Top Left
			1.0f, 1.0f, 0.0f // Top Right
	};

	/** The initial color definition */
	protected float m_colors[] = { 1.0f, 0.0f, 0.0f, 1.0f, // Top
			0.0f, 1.0f, 0.0f, 1.0f, // Bottom Left
			0.0f, 0.0f, 1.0f, 1.0f, // Bottom Right
	};

	public Square() {
		ByteBuffer bytebuffer = ByteBuffer
				.allocateDirect(m_vertices.length * 4);
		bytebuffer.order(ByteOrder.nativeOrder());
		m_vertexBuffer = bytebuffer.asFloatBuffer();
		m_vertexBuffer.put(m_vertices);
		m_vertexBuffer.position(0);

		bytebuffer = ByteBuffer.allocateDirect(m_colors.length * 4);
		bytebuffer.order(ByteOrder.nativeOrder());
		m_colorBuffer = bytebuffer.asFloatBuffer();
		m_colorBuffer.put(m_colors);
		m_colorBuffer.position(0);
	}

	/**
	 * The object own drawing function. Called from the renderer to redraw this
	 * instance with possible changes in values.
	 * 
	 * @param gl
	 *            - The GL context
	 */
	public void draw(GL10 gl) {
		// sets front face to counter clockwise
		gl.glFrontFace(GL10.GL_CCW);

		gl.glTranslatef(0.0f, 0.0f, -5.0f);
		gl.glScalef(0.5f, 0.5f, 0.5f);

		// point to our vertexbuffer
		gl.glVertexPointer(3, GL10.GL_FLOAT, 0, m_vertexBuffer);
		gl.glColorPointer(3, GL10.GL_FLOAT, 0, m_colorBuffer);

		// enable vertexbuffer
		gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
		gl.glEnableClientState(GL10.GL_COLOR_ARRAY);

		// draw the vertices as triangle strip
		gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, m_vertices.length / 3);

		// Disable the client state before leaving
		gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
		gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
	}

	public FloatBuffer getVertexBuffer() {
		return m_vertexBuffer;
	}

	public void setVertexBuffer(FloatBuffer a_vertexBuffer) {
		m_vertexBuffer = a_vertexBuffer;
	}

	public FloatBuffer getColorBuffer() {
		return m_colorBuffer;
	}

	public void setColorBuffer(FloatBuffer a_colorBuffer) {
		m_colorBuffer = a_colorBuffer;
	}

	public float[] getVertices() {
		return m_vertices;
	}

	public void setVertices(float[] a_vertices) {
		m_vertices = a_vertices;
	}

	public float getAngle() {
		return m_angle;
	}

	public void setAngle(float angle) {
		m_angle = angle;
	}
}
